<template>
  <div>
    <el-input
      class="address-input"
      disabled
      v-model="address"
      @click.native="show_map = true"
      placeholder="选择活动地点"
      size="small"
    ></el-input>
    <el-dialog :visible.sync="show_map" title="选择活动地址" width="1200">
      <el-row :gutter="16">
        <el-col :lg="12" :xs="24">
          <Location @getLoc="get_loc" :Location="adcode"/>
        </el-col>
        <el-col :lg="12" :xs="24">
          <el-input v-model="address" size="small">
            <el-button @click="show_map = false" slot="append" size="small">确定</el-button>
          </el-input>
        </el-col>
      </el-row>
      <el-divider/>
      <el-row class="map-area">
        <el-amap-search-box
          class="search-box"
          :search-option="searchOption"
          :on-search-result="onSearchResult"
        ></el-amap-search-box>
        <el-amap
          ref="map"
          :center="loc"
          :zoom="map.zoom"
          :plugin="map.plugin"
          :events="map.events"
          class="amap-box"
        >
          <el-amap-marker vid="component-marker" :position="loc"></el-amap-marker>
        </el-amap>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { AMapManager } from "vue-amap";
import Location from "@/components/Location";
import { lazyAMapApiLoaderInstance } from 'vue-amap';


export default {
  components: { Location },
  props: {
    mapAddress: Array,
    Address: String,
    lnglat: Array
  },
  data() {
    return {
      address: "",
      loc: ["121.472644", "31.231706"],
      location: {},
      amapManager: new AMapManager(),
      adcode: [],
      map: {
        zoom: 12,
        events: {
          init: o => {},
          // 地图点击事件
          click: e => {
            let lnglat = new Array();
            lnglat.push(e.lnglat.lng);
            lnglat.push(e.lnglat.lat);
            this.map.position = lnglat;
            this.loc = lnglat;
            let self = this;
            let { lng, lat } = e.lnglat;
            // 这里通过高德 SDK 完成。
            var geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: "all"
            });
            geocoder.getAddress([lng, lat], function(status, result) {
              if (status === "complete" && result.info === "OK") {
                if (result && result.regeocode) {
                  // 向表单插入位置数据
                  self.address = result.regeocode.formattedAddress;
                  self.$nextTick();
                }
              }
            });
          },
        },
        plugin: [
          "ToolBar",
          {
            pName: "MapType",
            defaultType: 0,
            events: {
              init(o) {}
            }
          }
        ]
      },
      // 位置搜索
      searchOption: {
        city: "上海",
        // 是否只搜索当前城市
        citylimit: true
      },
      show_map: false
    };
  },
  methods: {
    onSearchResult(pois) {
      let latSum = 0;
      let lngSum = 0;
      if (pois.length > 0) {
        pois.forEach(poi => {
          let { lng, lat } = poi;
          lngSum += lng;
          latSum += lat;
        });
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        };
        let ads = pois[0].name;
        this.loc = [center.lng, center.lat];
        this.set_address(this.location);
        this.address += ads;
      }
    },
    get_loc(row) {
      this.location = row;
      this.set_address(row);
      if (row.province) {
        if (row.city) {
          if (row.district) {
            this.loc = row.district.center?row.district.center.split(","):[];
            return;
          }
          this.loc = row.city.center?row.city.center.split(","):[];
          this.searchOption.city = row.city.name;
          return;
        }
        this.loc = row.province.center?row.province.center.split(","):[];
        this.searchOption.city = row.province.name;
      }
    },
    set_address(row) {
      let self = this;
      self.address = "";
      Object.keys(row).forEach(function(key) {
        // if(key == 'district') return;
        if (row[key]) {
          self.address += row[key].name;
          self.address += " ";
        }
      });
    }
  },
  mounted() {
    lazyAMapApiLoaderInstance.load().then(() => {
    //   // your code ...
    this.address = this.Address;

      // this.map = new AMap.Map("amapContainer", {
        // center: new AMap.LngLat(121.59996, 31.197646)
      // });
    });
  },
  watch: {
    lnglat(val) {
      this.loc = val;
    },    
    mapAddress(val) {
      this.adcode = val;
    },
    Address(val) {
      this.address = val;
    },
    address: {
      handler(nval) {
        let obj = {
          loc: this.location,
          address: nval,
          center: this.loc
        };
        this.$emit("getAddress", obj);
      }
    }
  }
};
</script>

<style scoped>
.main .address-input >>> input {
  color: inherit;
  background-color: inherit;
  cursor: pointer;
}
.map-area {
  position: relative;
}
.map-area .search-box {
  position: absolute;
  top: 20px;
  right: 120px;
}
.amap-box {
  height: 500px;
}
</style>
